package com.share.servlet;

import com.share.domain.BlogDomain;
import com.share.domain.BlogDomainImpl;
import com.share.entity.Blog;
import com.share.entity.User;
import com.share.servlet.utils.ForwardUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * Created by leep on 2016-01-11.
 */
public class AddBlogServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Blog blog = new Blog();
		String content = req.getParameter("content");
		blog.setCreateTime(new Timestamp(System.currentTimeMillis()));
		blog.setContent(content);
		User user = (User) req.getSession().getAttribute("user");
		blog.setUserId(user.getId());
		BlogDomain domain = new BlogDomainImpl();
		boolean result = domain.save(blog);
		if (result) {
			resp.sendRedirect("/");
		} else {
			req.setAttribute("msg", "添加错误");
			ForwardUtils.forward(req, resp, "/blog/add-blog.jsp", getServletContext());
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/blog/add-blog.jsp");
		dispatcher.forward(req, resp);
	}
}
